<template>
  <div class="login-container">
    <div class="login-form-container">
      <!-- 品牌标识 -->
      <div class="brand-logo">
        <div class="gradient-bg">
          <i class="el-icon"><component :is="brandIcon" /></i>
        </div>
        <h1 class="login-title">快速开发管理平台</h1>
        <p class="login-subtitle">请登录您的账号</p>
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-position="top"
        class="login-form"
      >
        <div class="form-group">
          <div class="form-label">用户名</div>
          <el-form-item prop="username">
            <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              :prefix-icon="User"
              clearable
              class="login-input"
            />
          </el-form-item>
        </div>
        
        <div class="form-group">
          <div class="form-label">密码</div>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              clearable
              @keyup.enter="submitForm"
              class="login-input"
            />
          </el-form-item>
        </div>
        
        <div class="remember-forgot">
          <el-checkbox v-model="rememberMe" class="remember-me">记住我</el-checkbox>
          <a href="#" class="forgot-link">忘记密码？</a>
        </div>
        
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-button"
            @click="submitForm"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { User, Lock, Collection } from '@element-plus/icons-vue'

// 获取路由实例
const router = useRouter()

// 表单引用
const loginFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 记住我选项
const rememberMe = ref(false)

// 表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ]
})

// 图标替换，使用Collection替代Cube图标
const brandIcon = Collection

// 提交表单
const submitForm = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    
    // 开始登录
    loading.value = true
    
    try {
      // 模拟API调用
      await handleLogin()
      ElMessage.success('登录成功')
      
      // 延迟导航，确保消息显示
      setTimeout(() => {
        // 使用路由导航到数据统计页面
        router.push({ path: '/data-analytics', replace: true })
      }, 1000)
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error)
      ElMessage.error(`登录失败：${errorMessage}`)
      console.error('登录失败:', error)
    } finally {
      loading.value = false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 处理登录逻辑
const handleLogin = async () => {
  // 模拟API调用延迟
  await new Promise(resolve => setTimeout(resolve, 800))
  
  // 检查用户名和密码（这里只是示例，实际应该使用API调用）
  if (loginForm.username === 'admin' && loginForm.password === 'admin123') {
    // 存储登录状态
    localStorage.setItem('isLoggedIn', 'true')
    localStorage.setItem('username', loginForm.username)
    localStorage.setItem('token', 'mock-token-' + Date.now())
    // 如果勾选了记住我，可以设置较长的过期时间
    if (rememberMe.value) {
      localStorage.setItem('rememberMe', 'true')
    }
    return true
  } else {
    throw new Error('用户名或密码不正确')
  }
}

// 检查用户是否已登录
onMounted(() => {
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  const token = localStorage.getItem('token')
  const remembered = localStorage.getItem('rememberMe') === 'true'
  
  if (remembered) {
    rememberMe.value = true
  }
  
  if (isLoggedIn && token) {
    console.log('用户已登录，准备跳转到插件管理页面')
    // 用户已登录，跳转到插件管理页面
    router.push({ path: '/plugin-manager', replace: true })
  } else {
    // 清除可能不完整的登录状态
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('token')
    localStorage.removeItem('username')
  }
})
</script>

<style scoped>
.login-container {
  height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-form-container {
  width: 430px;
  padding: 30px 40px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}

.brand-logo {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 25px;
}

.gradient-bg {
  width: 65px;
  height: 65px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12px;
  margin-bottom: 15px;
  background: linear-gradient(135deg, #f9b86d 0%, #f89e45 100%);
  color: white;
  font-size: 26px;
}

.login-title {
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 0;
  line-height: 1.3;
}

.login-subtitle {
  color: #606266;
  font-size: 14px;
  text-align: center;
  margin-top: 0;
  line-height: 1.3;
}

.login-form {
  margin-top: 10px;
}

.form-group {
  margin-bottom: 15px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 6px;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.remember-me {
  color: #333;
}

.forgot-link {
  font-size: 14px;
  color: #f89e45;
  text-decoration: none;
}

.login-button {
  width: 100%;
  border-radius: 8px;
  padding: 12px 0;
  font-size: 16px;
  background: linear-gradient(90deg, #f9b86d 0%, #f27121 100%);
  border: none;
  font-weight: 500;
}

.login-input {
  margin-bottom: 10px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  background-color: #f5f7fa;
  box-shadow: 0 0 0 1px #e4e7ed inset;
  height: 42px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #f89e45;
  border-color: #f89e45;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
  color: #333;
}
</style> 